package com.fengqianrun.java.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import com.aizuda.easy.security.code.BasicCode;
import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.domain.Req;
import com.aizuda.easy.security.exp.impl.BasicException;
import com.aizuda.easy.security.server.EasySecurityServer;
import com.aizuda.easy.security.util.AesEncryptUtil;
import com.aizuda.easy.security.util.LocalUtil;
import com.fengqianrun.java.domian.UserDTO;
import com.fengqianrun.java.domian.UserEntity;
import com.fengqianrun.java.domian.UserVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserController implements EasySecurityServer {

    List<UserEntity> db = Arrays.asList(
        new UserEntity("1","张三","zhangsan",Arrays.asList("/goods/buy","/user/updateCurrentName","/user/selectInfo")),
        new UserEntity("2","李四","lisi",Arrays.asList("/user/updateCurrentName","/user/selectInfo")),
        new UserEntity("3","王五","wangwu",Arrays.asList("/goods/buy","/user/selectInfo")),
        new UserEntity("4","赵六","zhaoliu",Arrays.asList("/goods/buy","/user/updateCurrentName")),
        new UserEntity("5","田七","tianqi",Arrays.asList("/goods/buy","/user/updateCurrentName","/user/selectInfo"))
    );


    @Value("key")
    private String key;

@PostMapping("/login")
public Rep<UserVO> login(@RequestBody Req<UserDTO,UserVO> req){
    UserDTO userDTO = req.getData();
    if(StrUtil.isEmpty(userDTO.getAccount()) || StrUtil.isEmpty(userDTO.getPassword())){
        return Rep.error(500,"账号或密码错误");
    }
    // 数据库查询
    UserEntity user = db.stream().filter(i -> i.getAccount().equals(userDTO.getAccount())).findAny().get();
    UserVO userVO = new UserVO();
    BeanUtil.copyProperties(user,userVO,"account");
    String token = JWT.create()
            .setPayload("id",user.getId())
            .setPayload("name",user.getName())
            .setPayload("exp", System.currentTimeMillis()+60*60*1000)
            .setPayload("url", userVO.getUrl())
            .setKey(key.getBytes())
            .sign();
    userVO.setToken(token);
    return Rep.ok(userVO);
}

    @PostMapping("/updateCurrentName")
    public Rep<UserVO> updateName(@RequestBody Req<String,UserVO> req){
        UserVO userVO = req.getUser();
        String name = req.getData();
        db = db.stream().map(i -> {
            if(userVO.getId().equals(i.getId())){
                i.setName(name);
            }
            return i;
        }).collect(Collectors.toList());
        return Rep.ok();
    }

    @PostMapping("/selectInfo")
    public Rep<UserEntity> selectInfo(@RequestBody Req<String,UserVO> req){
        UserVO userVO = req.getUser();
        UserEntity user = db.stream().filter(i -> i.getId().equals(userVO.getId())).findAny().get();
        return Rep.ok(user);
    }



    @Override
    public Object getAuthUser(String token) throws BasicException {
        JWT jwt = JWT.of(token);
        // 验证
        if(!jwt.setKey(key.getBytes()).verify()){
            throw new BasicException(BasicCode.BASIC_CODE_99986);
        }
        // 是否失效
        Long exp = Long.valueOf(jwt.getPayload("exp").toString());
        if(System.currentTimeMillis() > exp){
            throw new BasicException(BasicCode.BASIC_CODE_99985);
        }
        // 返回用户
        UserVO userVO = new UserVO();
        userVO.setId(jwt.getPayload("id").toString());
        userVO.setName(jwt.getPayload("name").toString());
        userVO.setUrl((List<String>) jwt.getPayload("url"));
        return userVO;
    }

    @Override
    public List<String> getAuthorizeUrl(String token) throws BasicException{
        UserVO userVO = (UserVO) getAuthUser(token);
        return userVO.getUrl();
    }

    public static void main(String[] args) {
        String key = "1111111111111111";

//        Req<Map<String,Object>,Object> req = new Req<>();
//        Map<String,Object> map = new LinkedHashMap<>();
//        map.put("account", "zhangsan");
//        map.put("password", "321321");
//        req.setData(map);
//        System.out.println(AesEncryptUtil.encryption(JSONUtil.toJsonStr(req), key, "2222222222222222"));

        String json = "xU4V+hfKOoN/UFxNAd1014qe6zrB0p+8i+JNeMQ2mSt+edVOkQ2nniuUAeoSxSxMzLTX8jNrtKM3+fsVPdYjiTqxB7m0aTfrBO/RXXmfVYq/c16dLH8E4iuwcXHUMmyMbcr8eqERjOCv3e9AwaXMhgeSlW2KzEfBdCwFfxrRayHq6sfkcovViI406M8/sAhhnFdtOhXaJcNOMSRzEFUEgY1jz+PfvAd4yjhz66/ZCZ5jN6RM3bxSGXJ2SMcmpQKNiM/c/VPJXa/oq4ZTAKJDNxZXZsDuVql6mnQlUUsBi+H3NeJLE6IWJ8IxyIOxkmDcsrfAdfYF4170l8/vTWcewyzCv4z1VZkuepwdhN2CJj5wgAiNjh6P0+BGvFoSHg7aBy56GYPLKQtMjfMioWnX8IP5Q2stPDnxuB6hMG0qCTXZHzgZf9X9WUR0B8uUgoKrsslxH9oS5iO1WBg8s52YMquL9ZOj7Ds5znBu68yygUVVnVHMsaMC2UJo8WxJQUOf";
        System.out.println(AesEncryptUtil.decryption(json, key, "814e6e03ebfb550a"));
    }

}
